from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import NotAuthenticated
from .token_module import out_token
from common.constant import CODE_AUTH_ERROR, MSG_AUTH_ERROR


class TokenAuth(BaseAuthentication):
    def authenticate(self, request):
        try:
            # 数据放在header内传输，request.META获取
            # meta查询key值格式：HTTP_大写字段名 例如：auth-token - HTTP_AUTH_TOKEN
            token = request.META.get("HTTP_AUTH_TOKEN")
            username = request.META.get("HTTP_USERNAME")
            if token == None:
                raise NotAuthenticated(
                    detail=MSG_AUTH_ERROR, code=CODE_AUTH_ERROR)
            if username == None:
                raise NotAuthenticated(
                    detail=MSG_AUTH_ERROR, code=CODE_AUTH_ERROR)

            token_obj = out_token(username, token)
            if token_obj:
                return
            else:
                raise NotAuthenticated(
                    detail=MSG_AUTH_ERROR, code=CODE_AUTH_ERROR)
        except Exception:
            raise NotAuthenticated(detail=MSG_AUTH_ERROR, code=CODE_AUTH_ERROR)
